using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using YushengMall.Backend.Api.Entity;
using YushengMall.Backend.Api.ParamModel;
using YushengMall.Backend.Api.Params;

namespace YushengMall.Backend.Api.Controllers
{
    [Controller]
    [Route("[controller]")]
    public class AuthenticationController : ControllerBase
    {
        private readonly TokenParameter _tokenParameter = new TokenParameter();
        public AuthenticationController()
        {
            var config = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
            _tokenParameter = config.GetSection("TokenParameter").Get<TokenParameter>();
        }

        [HttpPost, Route("requesttoken")]
        public ActionResult RequestToken([FromBody] UserLogins request)
        {

            if (request.UserName == "" && request.Password == "")
            {
                return BadRequest("Invalid Request");
            }

            // var claims = new[]{
            //     new Claim(ClaimTypes.Name,request.UserName),
            //     new Claim(ClaimTypes.Role,"")
            // };
            /// <summary>
            /// 生成token和RefreshToken
            /// </summary>
            /// <returns></returns>
            var token = GenUserToken(request.UserName, "");
            var refreshToken = "123456";
            return Ok(new[] { token, refreshToken });
        }

        private string GenUserToken(string UserName, string Role)
        {
            var claims = new[]{
                new Claim(ClaimTypes.Name,UserName),
                new Claim(ClaimTypes.Role,Role)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(_tokenParameter.Issuer, null, claims,
                expires: DateTime.UtcNow.AddMinutes(_tokenParameter.accessExpiration),
                signingCredentials: credentials);
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return token;
        }

        [HttpPost, Route("refreshtoken")]
        public ActionResult Refreshtoken([FromBody] RefreshTokenParameter request)
        {
            if (request.Token == null && request.RefreshToken == null)
            {
                return BadRequest("invalid Request");
            }

            var handler = new JwtSecurityTokenHandler();

            try
            {
                ClaimsPrincipal claim = handler.ValidateToken(request.Token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_tokenParameter.Secret)),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                },
                out SecurityToken securityToken
                );
                var username = claim.Identity.Name;

                var Token = GenUserToken(username, "");
                var refreshtoken = "654321";
                return Ok(new[] { Token, refreshtoken });
            }
            catch (Exception)
            {
                return BadRequest("Invalid Request");
            }


        }
    }
}